# GPL 3
import os
import sys
import traceback
import time
import datetime
import random
import threading
import json


import youtube

from ui import *


def add(username, videoId, title, duration):

    # This fucntion adds the song into the video
    with open('stuff.json') as json_file: 
        stuff = json.load(json_file)

    if "users" not in stuff:
        stuff["users"] = {}
        
    if username not in stuff["users"]:
        avatar = "https://matrix.org/_matrix/client/v3/profile/"+username+"/avatar_url"
        stuff["users"][username] = {"display_name":username,
                                    "avatar":avatar,
                                    "now":[],
                                    "history":[]}

    
    if videoId not in stuff["users"][username]["now"]:
        stuff["users"][username]["now"].append(videoId)
        
    if videoId not in stuff["users"][username]["history"]:
        stuff["users"][username]["history"].append(videoId)

    if "songs" not in stuff:
        stuff["songs"] = {}
        
    if videoId not in stuff["songs"]:
        stuff["songs"][videoId] = {"title":title,
                                   "file":None,
                                   "duration":duration,
                                   "timestamp":int(time.time())}
    with open('stuff.json', 'w') as fp:
        json.dump(stuff, fp, indent=4)

    
        
    time.sleep(1)    
    with open('stuff.json') as json_file: 
        stuff = json.load(json_file)

    ind = -1
    for n, i in enumerate(stuff["users"][username]["history"]):
        if i == videoId:
            ind = n
    if videoId in stuff["users"][username]["history"] and ind > -1:
        return ind
    
    else:
        print("    [ NOT ADDED ] Trying again:", videoId)
        # Try again
        add(username, videoId, title, duration)


def execute(username, message, password=""):

    THE_RETURN = ""


    with open('stuff.json') as json_file: 
        stuff = json.load(json_file)
                
    new_date_format = "%Y/%m/%d"
    today = datetime.datetime.strftime(datetime.datetime.today(), new_date_format)
    for d in range(400):
        yesterday = datetime.datetime.strftime(datetime.datetime.today()-datetime.timedelta(days=d+1), new_date_format)
        if yesterday in stuff.get("volume", {}):
            break
            
    matrix_username = stuff.get("matrix", {}).get("username")


    adduser = False
    if matrix_username != username:
        adduser = True

    # Make a list
    addlist = []


    for inst in youtube.all_instances:
        for line in str(message).split("\n"):
            if inst in line and "🔗" not in line:
                videoId = youtube.strip(line)
                addlist.append(videoId)

    # Commands
    sendback_number = username+" 👍️\n\n"
    tosend_number = False



    for line in str(message).split("\n"):


        with open('stuff.json') as json_file: 
            stuff = json.load(json_file)

        line = line.lower()
        if line.endswith(" "):
            line = line[:-1]

        # Last
        try:
            last = len(stuff.get("users", {}).get(username, {}).get("now", []))-1
        except:
            last = 0
        if not last:
            try:
                last = len(stuff.get("users", {}).get(username, {}).get("history", []))-1
            except:
                last = 0
        else:
            try:
                last = stuff.get("users", {}).get(username, {}).get("now", [])[last]
                last = stuff.get("users", {}).get(username, {}).get("history", []).index(last)
            except:
                pass
        line = line.replace("last", str(last)).replace("אחרון", str(last))

        try:


            song = stuff.get("users", {}).get(username, {}).get("history", [])[int(line)]
            if song not in stuff["users"][username]["now"]:
                stuff["users"][username]["now"].append(song)
            sendback_number = sendback_number + "🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** \n\n"
            tosend_number = True
            with open('stuff.json', 'w') as fp:
                json.dump(stuff, fp, indent=4)

            continue
        except:
            # Maybe the person is trying to move the songs arround
            try:

                fro = int(line.split(" ")[0])
                to  = int(line.split(" ")[1])

                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)

                song = stuff.get("users", {}).get(username, {}).get("history", [])[fro]

                try:
                    stuff["users"][username]["now"].insert(to, song)
                except:
                    stuff["users"][username]["now"].append(song)

                sendback_number = sendback_number + "🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** -- `"+str(to)+"` \n\n"
                tosend_number = True
                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

                continue
            except Exception as e:

                # Maybe the person is trying to insert whole ranges of stuff
                try:
                    fromlist = line.split(" ")[0].split(":")
                    to  = int(line.split(" ")[1])

                    with open('stuff.json') as json_file: 
                        stuff = json.load(json_file)

                    sendback_number = ""

                    for fro in reversed(range(int(fromlist[0]), int(fromlist[1])+1)):
                        try:
                            song = stuff.get("users", {}).get(username, {}).get("history", [])[fro]

                            try:
                                stuff["users"][username]["now"].insert(to, song)
                            except:
                                stuff["users"][username]["now"].append(song)

                            sendback_number = "🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** \n" + sendback_number
                            tosend_number = True
                        except:
                            pass
                    sendback_number = sendback_number + " -- `"+str(to)+"`"
                    with open('stuff.json', 'w') as fp:
                        json.dump(stuff, fp, indent=4)

                    continue
                except Exception as e:
                    pass

        if line == "help":
            adduser = True
            help_text = username+"""
`help` ✍ This help message.
`now` ✍ Info about the currently playing song.
`history` ✍ Song you've sent ever.
`list` ✍ Song you have currently in the playlist.
`<number>` ✍ Add a song from those you've sent.
`last` ✍ Gives you your last song's index. *( Useful for putting it closer up )*-
`<number> <number>` ✍ Chosse song from histroy and insert it in a particular place in playlist.
`all` ✍ Add all your songs back *( randomly )*.
`random` ✍ Add a random song from yours.
`delete <number>` ✍ Delete a song from history. *(Also from the list)*
`skip` ✍ Skip **your own** song. 
`votes` ✍ See the volume vote results.
`people` ✍ List people that sent songs.
`exit` ✍ Exit from the day presence.
`search <query>` Search on YouTube.
"""
            if password:
                help_text = """
<center>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=list">⬆ List</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=history">🎸 History</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=all">🎸🎸 All</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=random">❔ Random</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=skip">⏭ Skip</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=set_volume">🔈 Volume</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=songs">🎶 All Songs</a>

<a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=exit">😞 Exit</a>

</center>
"""
            (help_text.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(help_text)


        elif "עזרה" in line and not "`" in line:
            adduser = True
            help_text = username+"""
`עזרה` ✍ נותן לך עזרה.
`עכשיו` ✍ נותן מידע על השיר שמנגן כרגע.
`היסטוריה` ✍ רשימה של כל השירים ששלחת.
`רשימה` ✍ נותן שירים שנישארו להתנגן.
`<מיספר>` ✍ מיספר של שיר מההיסטוריה להוסיף לסוף של הרשימה.
`<מיספר> <מיספר>` ✍ לישלוח שיר מההיסטוריה למקום מדויק לרשימה.
`אחרון` ✍ נותן את השיר האחרון.
`הכל` ✍ להוסיף את כל השירים מההיסטוריה לרשימה.
`רנדומלי` ✍ להוסיף שיר רנדומלי מההיסטוריה לרשימה.
`מחק <מיספר>` ✍ מחק שיר מהיסטוריה ומהרשימה.
`לדלג` ✍ דלג על השיר שלך.
`ווליום` ✍ היםטוריה של הווליום.
`אנשים` ✍ רשימה של קול הנשים.
`לצאת` ✍ אמור למחשב שאתה הולך הביתה. אז זה יפסיק לנגן את השירים שלך.
"""

            THE_RETURN = THE_RETURN + str(help_text)

        elif ("votes" in line or ("ווליום" in line and "`" not in line)) and " " not in line and "🎸" not in line:
            adduser = True
            with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)
            answer = username+"\n\n"
            for day in stuff.get("volume", {}):
                try:
                    answer = answer + "\n\n 🗓️ "+day+": "+str(round(stuff["volume"][day]["average"], 1))+"%"
                except:
                    pass
            (answer.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(answer)


        elif line == "people" or ("אנשים" in line and "`" not in line):
            adduser = True
            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            answer = username+"\n\n"

            for u in stuff.get("users", {}):
                answer = answer + "\n"
                answer = answer + user_emoji(u, stuff)+"\n"
                answer = answer + "🎸 "+str(len(stuff.get("users", {}).get(u, {}).get("now", [])))+"\n"
                answer = answer + "🔗 "+str(len(stuff.get("users", {}).get(u, {}).get("history", [])))+"\n"
                answer = answer + "😈 "+str(round(stuff.get("users", {}).get(u, {}).get("evil", 0),2))+"%\n"

            (answer.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(answer)

        elif line.startswith("eval "):
            command = line[line.find(" ")+1:]
            answer = username+"\n\n"
            try:
                answer = answer + "Answer: `"+ str(eval(command)).replace("\n", "\\n")+"`"
            except Exception as e:
                answer = answer + "Error:  `"+str(e).replace("\n", "\\n")+"`"

            (answer.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(answer)

        elif line.startswith("search "):
            command = line[line.find(" ")+1:]
            answer = username+"\n\n"

            search_data = youtube.search(command)
            for i in search_data:
                if i["type"] == "video" and i["lengthSeconds"] < 10*60 and i["lengthSeconds"]:
                    if password:
                        answer = answer + "![]("+i["videoThumbnails"][0]["url"]+")"
                    answer = answer + "🎸 " +i["title"].replace("[", "_").replace("]", "_")+ "\n"
                    answer = answer + "🔗 "+"https://yewtu.be/"+i["videoId"]+"\n"
                    answer = answer + "🧑‍ "+i["author"]+"\n"
                    answer = answer + "👁️ "+str(i["viewCount"])+"\n"
                    answer = answer + "⏰ "+timestring(i["lengthSeconds"])+"\n\n"
                    
                    if password:
                        answer = answer + '<a class="button" href="/?user_name='+username+'&password='+password+'&item='+"https://yewtu.be/"+i["videoId"]+'">➕</a>\n\n'

            THE_RETURN = THE_RETURN + str(answer)
            
        elif "songs" in line and "'" not in line and "🎸" not in line:
            adduser = True
            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            answer = username+"\n\n"

            n = 1
            for s in stuff.get("songs", {}):

                date_is = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(stuff.get("songs", {}).get(s, {}).get("timestamp", s)))

                if " " in line:
                    search_term = line[line.find(" ")+1:]

                    if ">" in search_term or "<" in search_term:
                        answer_is_ = eval(str(stuff.get("songs", {}).get(s, {}).get("duration", 0))+" "+search_term)
                        if not answer_is_:
                            continue

                    elif search_term.lower() not in stuff.get("songs", {}).get(s, {}).get("title", s).lower() and search_term.lower() not in date_is.lower():
                        continue



                n = n + 1

                if n % 100 == 0:
                    (answer.replace("\n", "\n                  "))
                    THE_RETURN = THE_RETURN + str(answer)
                    answer = ""



                answer = answer + "\n"
                answer = answer + "🎸 "+stuff.get("songs", {}).get(s, {}).get("title", s).replace("[","_").replace("]", "_")+"\n"
                answer = answer + "⏰ "+timestring(stuff.get("songs", {}).get(s, {}).get("duration", s))+"\n"

                answer = answer + "🗓 "+str(date_is)+"\n"
                answer = answer + "🔗 "+"https://yewtu.be/"+s+"\n"
                
                
                
                # Look in users
                for u in stuff.get("users", {}):
                    if s in stuff.get("users", {}).get(u, {}).get("history", []):
                        try:
                            ind = "Index: "+str(stuff.get("users", {}).get(u, {}).get("history", []).index(s))
                        except:
                            ind = ""
                        answer = answer + user_emoji(u, stuff)+" "+ind+"\n"
                        break
                if password and s not in stuff.get("users", {}).get(username, {}).get("history", []):
                        answer = answer + '<a class="button" href="/?user_name='+username+'&password='+password+'&item='+"https://yewtu.be/"+s+'">➕</a>\n\n'
                elif password:
                    answer = answer + '<a class="button" href="/?user_name='+username+'&password='+password+'&item='+str(stuff.get("users", {}).get(username, {}).get("history", []).index(s))+'+0">⬆</a>\n\n'
            (answer.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(answer)

        elif "%" in line and " " not in line and "`" not in line:
            adduser = True
            try:
                percent = min(100,max(0,float(line.replace("%", ""))))

                vote_message = ""

                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)


                try:
                    was = stuff["volume"][today]["users"][username]
                except:
                    was = 50

                # Evil
                evil = 50
                if stuff.get("now_username") != username and percent < was:
                    evil = was + (was - percent)
                elif stuff.get("now_username") == username and percent > was:
                    evil = was + (percent - was)
                elif stuff.get("now_username") == username and percent < was:
                    evil = was - (was - percent)
                elif stuff.get("now_username") != username and percent > was:
                    evil = was - (percent - was)

                evil = min(100, max(0, evil))

                try:
                    previl = stuff.get("users", {}).get(username, {}).get("evil", 50)
                    stuff["users"][username]["evil"] = (previl+evil)/2
                except Exception as e:
                    print(e)

                try:
                    if "volume" not in stuff:
                        stuff["volume"] = {}
                    if today not in stuff["volume"]:
                        stuff["volume"][today] = {"users":{}}
                    stuff["volume"][today]["users"][username] = percent
                except Exception as e:
                    print(e)
                    pass

                the_numbers = []

                for u in stuff.get("present", {}).get(today, []):

                    ifu = ""
                    if u == username:
                        ifu = "# "
                    vote_message = vote_message + "\n"+ifu+" "+user_emoji(u, stuff)+" *voted:* "+(str(stuff.get("volume", {}).get(today, {}).get("users", {}).get(u, "kaka"))+"%").replace("kaka%", "💩 *("+str(round(stuff.get("volume", {}).get(yesterday, {}).get("average", 20),1))+"%)* ")
                    the_numbers.append(stuff.get("volume", {}).get(today, {}).get("users", {}).get(u, stuff.get("volume", {}).get(yesterday, {}).get("average", 20)))

                try:
                    average = sum(the_numbers)/len(the_numbers)
                    stuff["volume"][today]["average"] = average
                except:
                    average = 0

                vote_message = vote_message + "\n\n`"
                for n, tn in enumerate(the_numbers):
                    plus = "( "
                    if n != 0:
                        plus = " + "
                    vote_message = vote_message + plus+str(round(tn, 1))
                vote_message = vote_message + " ) / "+str(len(the_numbers))+"` = "+str(round(average, 1))+"%"

                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

            except Exception as e:
                vote_message = username+" 💩\n\n*("+str(e)+")* "


            (vote_message.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(vote_message)

        elif line == "set_volume":

            volume_was = stuff.get("volume", {}).get(today, {}).get("users", {}).get(username, stuff.get("volume", {}).get(yesterday, {}).get("average", 20))

            volume_users = stuff.get("volume", {}).get(today, {}).get("users", {})
            THE_RETURN = """<center><details><summary>"""

            emojis = "😀😒😗🤣😖🙂🤣😁🤪"
                        
            for u in stuff.get("present", {}).get(today, {}):
                THE_RETURN = THE_RETURN + random.choice(emojis)
            present_is = len(stuff.get("present", {}).get(today, []))
            THE_RETURN = THE_RETURN +" ( "+str(int(100/present_is))+"% each )</summary>"
            maxnums = []
            minnums = []
            for u in stuff.get("present", {}).get(today, []):
                THE_RETURN = THE_RETURN +"<br> "+user_emoji(u, stuff)+" *voted:* "+(str(stuff.get("volume", {}).get(today, {}).get("users", {}).get(u, "kaka"))+"%").replace("kaka%", "💩 *("+str(round(stuff.get("volume", {}).get(yesterday, {}).get("average", 20),1))+"%)* ")

                thenumber = stuff.get("volume", {}).get(today, {}).get("users", {}).get(u, stuff.get("volume", {}).get(yesterday, {}).get("average", 20))
                if u == username:                    
                    maxnums.append(100)
                    minnums.append(0)
                else:
                    maxnums.append(thenumber)
                    minnums.append(thenumber)

            try:
                maxis = int( round( sum(maxnums) / len(maxnums) ))
            except:
                maxis = 100
            try:
                minis = int( round ( sum(minnums) / len(minnums) ))
            except:
                minis = 0
            
                
            THE_RETURN = THE_RETURN + "</details>"
            
            THE_RETURN = THE_RETURN +"""<br>
            <form action="/" method="GET">
            <ul><li>"""+str(minis)+"""%</li><li>"""+str(maxis)+"""%</li></ul>
            <input id="user_name" name="user_name" type="hidden" value='"""+username+"""'>
            <input id="password" name="password" type="hidden" value='"""+password+"""'>
            <input type="range" min="0" max="100" value=\""""+str(volume_was)+"""\" class="slider" id="volume" name="volume"><br>
            <button type="submit">🔈 Vote 🔈</button>
            </form></center>
                
            """
            
        elif line == "list" or ("רשימה" in line and "`" not in line):
            adduser = True
            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)
            list_to_send = username+"\n\n"
            
            for n , song in enumerate(stuff.get("users", {}).get(username, {}).get("now", [])):
                if password:
                    list_to_send = list_to_send + "<ul><li>"
                list_to_send = list_to_send + "*" + str(n)+ "* 🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song).replace("<", "_").replace(">", "_").replace("[", "_").replace("]", "_")+"**"

                if password:
                    try:
                        indexis = stuff.get("users", {}).get(username, {}).get("history", []).index(song)
                    except:
                        indexis = 0
                    list_to_send = list_to_send + '</li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item='+str(indexis)+'+0">⬆</a></li></ul></div><br><br>\n\n'

                
                #list_to_send = list_to_send + "\n"
                if not password:
                    list_to_send = list_to_send + "\n\n"

            (list_to_send.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(list_to_send)

        elif (("history" in line and "`" not in line) or ("היסטוריה" in line and "`" not in line)) and "🎸" not in line:
            adduser = True
            list_to_send = username+"\n\n"

            search_term = ""

            # Search term
            if " " in line:
                search_term = line[line.find(" ")+1:]
                list_to_send = list_to_send + "🔍 `"+search_term.lower()+"` \n\n"

            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)
            con = 0

            history_is = stuff.get("users", {}).get(username, {}).get("history", [])

            # if user searches ranges

            if ":" in search_term:
                try:
                    history_is = eval("history_is["+search_term+"]")
                    search_term = ""
                except:
                    pass

            for n , song in enumerate(history_is):

                try:
                    n = stuff.get("users", {}).get(username, {}).get("history", []).index(song)
                except:
                    pass

                con = con + 1
                if search_term and search_term.lower() not in stuff.get("songs", {}).get(song, {}).get("title", song).lower():
                    continue
                if password:
                    list_to_send = list_to_send + '<div class"ulcont"><ul><li>'
                list_to_send = list_to_send + "`" + str(n)+ "` 🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** \n\n"
                if password:
                    list_to_send = list_to_send + '</li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item='+str(n)+'+0">⬆</a></li></ul></div><br><br>\n\n'

            (list_to_send.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(list_to_send)

        elif (line == "all" or ("הכל" in line and "`" not in line) ) and "🎸" not in line:
            adduser = True
            try:
                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)

                songs = stuff.get("users", {}).get(username, {}).get("history", []).copy()
                while songs:
                    song = songs.pop(random.choice(range(len(songs))))
                    if song not in stuff["users"][username]["now"]:
                        stuff["users"][username]["now"].append(song)
                    sendback_number = sendback_number + "🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** \n\n"
                    tosend_number = True
                    with open('stuff.json', 'w') as fp:
                        json.dump(stuff, fp, indent=4)
            except:
                pass

        elif line == "skip" and " " not in line:
            adduser = True

            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            if username == stuff.get("now_username", ""):
                stuff["skip"] = True
                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

                send_skip = username+" 👍\n\n Skipping!"
            else:
                send_skip = username+" 💩\n\n You have no right to skip this song!\n\n Ask: "+user_emoji(stuff.get("now_username", ""), stuff)+" to skip."

            (send_skip.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(send_skip)

        elif  "לדלג" in line and "`" not in line and " " not in line:
            adduser = True

            with open('stuff.json') as json_file: 
                stuff = json.load(json_file)

            if username == stuff.get("now_username", ""):
                stuff["skip"] = True
                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

                send_skip = username+" 👍\n\n מדלגים עכשיו!"
            else:
                send_skip = username+" 💩\n\n אין לך זכות לדלג על השיר הזה!\n\n תשאל מ: "+user_emoji(stuff.get("now_username", ""), stuff)+"."

            (send_skip.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(send_skip)

        elif line.startswith("delete ") or ("מחק" in line and "`" not in line):
            adduser = True
            try:
                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)
                song = stuff.get("users", {}).get(username, {}).get("history", [])[int(line.split(" ")[1])]
                stuff["users"][username]["history"].remove(song)
                try:
                    stuff["users"][username]["now"].remove(song)
                except:
                    pass

                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

                mes = username + "\n\n 🚫 "+ stuff.get("songs", {}).get(song, {}).get("title")

                (mes.replace("\n", "\n                  "))
                THE_RETURN = THE_RETURN + str(mes)
            except Exception as e:
                mes = username + "\n\n 💩 "+str(e)

                (mes.replace("\n", "\n                  "))
                THE_RETURN = THE_RETURN + str(mes)

        elif (line == "now"  or ("עכשיו" in line and "`" not in line)) and "🎸" not in line:
            adduser = True
            song_info = "🎸 "+stuff.get("songs", {}).get(stuff.get("now_playing", ""), {}).get("title")
            song_info = song_info + "\n⏰ "+timestring(stuff.get("songs", {}).get(stuff.get("now_playing", ""), {}).get("duration"))
            song_info = song_info + "\n🔗 https://yewtu.be/"+stuff.get("now_playing", "")
            song_info = song_info +"\n "+user_emoji(stuff.get("now_username", ""), stuff)

            (song_info.replace("\n", "\n                  "))
            THE_RETURN = THE_RETURN + str(song_info)

        elif (line == "random" or ("רנדומלי" in line and "`" not in line)) and "🎸" not in line:
            try:
                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)


                song = random.choice(stuff.get("users", {}).get(username, {}).get("history", []))
                if song not in stuff["users"][username]["now"]:
                    stuff["users"][username]["now"].append(song)
                sendback_number = sendback_number + "🎸 **"+stuff.get("songs", {}).get(song, {}).get("title", song)+"** \n\n"
                tosend_number = True
                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)
            except Exception as e:
                print( e)

        elif (line == "exit" or ("לצאת" in line and "`" not in line)) and "🎸" not in line:

            adduser = False
            try:
                with open('stuff.json') as json_file: 
                    stuff = json.load(json_file)
                print(stuff["present"][today])
                stuff["present"][today].remove(username)
                print(stuff["present"][today])

                with open('stuff.json', 'w') as fp:
                    json.dump(stuff, fp, indent=4)

                exitinfo = "Exited!"

                (exitinfo.replace("\n", "\n                  "))
                THE_RETURN = THE_RETURN + str(exitinfo)
            except:
                pass


    if tosend_number:
        (sendback_number.replace("\n", "\n                  "))
        THE_RETURN = THE_RETURN + str(sendback_number)


    if addlist:
        (username+" ⏰".replace("\n", "\n                  "))
        THE_RETURN = THE_RETURN + str(username+" ⏰")

    # Shuflle the list
    shuffled = []
    while addlist:
        shuffled.append(addlist.pop(random.choice(range(len(addlist)))))


    # Extract playlists
    final = []
    okay = []
    for videoId in shuffled:

        # PlaylistIDs are about 3 times longer than videoIDs
        if len(videoId) > 11:
            print("        [ "+clr["bold"]+clr["tbyl"]+"PLAYLIST"+clr["norm"]+" ] "+videoId)
            playlist = youtube.fetch_playlist(videoId)
            if type(playlist) is not str:
                for song in playlist.get("videos", []):
                    if song.get("videoId", ""):
                        final.append(song.get("videoId", ""))
            else:
                okay.append("💩 **"+videoId+"** \n\n"+str(playlist))
        else:
            final.append(videoId)

    # Adding songs into list
    fsi = 0
    for videoId in final:

        info = youtube.fetch_info(videoId)
        length = info.get("lengthSeconds", 9999999999999999)
        title = info.get("title", "")

        if length < 60*14: # 13 minutes max


            print("        [   "+clr["tbgr"]+"OKAY"+clr["norm"]+"   ] "+videoId+" | "+timestring(length))
            si = add(username, videoId, title, length)
            if not fsi:
                fsi = si
            adduser = True
            okay.append("🎸 ("+str(si)+") **"+title+"** \n\n")

        else:
            print("        [ "+clr["tbrd"]+"TOO LONG"+clr["norm"]+" ] "+videoId+" | "+timestring(length))
            okay.append("💩 **"+title+"** \n\n")

    if password and final:
        okay.append('\n\n<a class="button" href="/?user_name='+username+'&password='+password+'&item='+str(fsi)+':'+str(si)+'+0">⬆</a>\n\n')
        
        
    if okay:
        send_back = username+" 👍️\n\n"
        for i in okay:
            send_back = send_back + i

        (send_back.replace("\n", "\n                  "))
        THE_RETURN = THE_RETURN + str(send_back)

    if "`" in str(message) or "🎸" in str(message):
        adduser = False

    # Adding user to present
    if "present" not in stuff:
        stuff["present"] = {}
    if today not in stuff["present"]:
        stuff["present"][today] = []
    if username not in stuff["present"][today] and adduser:
        stuff["present"][today].append(username)

        with open('stuff.json', 'w') as fp:
            json.dump(stuff, fp, indent=4)
            
    return THE_RETURN
